<template>
  <div class="app-container">
    <el-row>
      <el-col :span="24" class="card-box">
        <el-card>
          <div class="head-row">
            <div class="head">统计图表展示</div>
            <div class="tab">
              <div
                :class="current === 0 ? 'tab-item active' : 'tab-item'"
                @click="
                  current = 0;
                  getUserList();
                "
              >
                民警统计
              </div>
              <div
                :class="current === 1 ? 'tab-item active' : 'tab-item'"
                @click="
                  current = 1;
                  getComList();
                "
              >
                社区统计
              </div>
            </div>
          </div>
          <template v-if="current === 0">
            <el-row class="mt1">
              <el-form-item label="民警" prop="badgeNumber">
                <el-select
                  v-model="policeUserId"
                  filterable
                  placeholder="请输入民警姓名或警号搜索"
                  style="width: 240px"
                  @change="initUserEvaStat"
                >
                  <el-option
                    v-for="item in polices"
                    :key="item.policeUserId"
                    :label="`${item.userName}-${item.badgeNumber}`"
                    :value="item.policeUserId"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="时间" class="ml4">
                <el-date-picker
                  v-model="userYears"
                  type="year"
                  placeholder="请选择"
                  format="YYYY年"
                  value-format="YYYY"
                  @change="getUserList"
                />
              </el-form-item>
              <el-form-item class="ml4">
                <el-button type="primary" icon="Search" @click="getUserList"
                  >查询</el-button
                >
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-row>
            <el-row class="mt1" :gutter="50">
              <el-col :span="12">
                <div ref="evayear" style="height: 300px" />
              </el-col>
              <el-col :span="12">
                <el-radio-group
                  v-model="scoreStar"
                  @change="initUserEvaStatSort()"
                >
                  <el-radio :value="10">全部</el-radio>
                  <el-radio :value="3">满意</el-radio>
                  <el-radio :value="2">一般</el-radio>
                  <el-radio :value="1">不满意</el-radio>
                </el-radio-group>
                <div ref="evanum" style="height: 300px" />
              </el-col>
            </el-row>
            <div
              class="mt2 el-table el-table--enable-row-hover el-table--medium"
            >
              <el-table v-loading="loading" :data="tableList1" border>
                <el-table-column label="时间" prop="months" align="center">
                  <template #default="scope">
                    {{
                      scope.row.months != "全部"
                        ? scope.row.months + "月"
                        : scope.row.months
                    }}
                  </template>
                </el-table-column>
                <el-table-column
                  label="评价总数"
                  prop="sumCount"
                  align="center"
                >
                  <template #default="scope">
                    <span style="color: #038afe">{{ scope.row.sumCount }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="满意"
                  prop="satisfiedCount"
                  align="center"
                />
                <el-table-column
                  label="一般"
                  prop="generalCount"
                  align="center"
                />
                <el-table-column
                  label="不满意"
                  prop="unsatisfiedCount"
                  align="center"
                />
              </el-table>
            </div>
          </template>
          <template v-if="current === 1">
            <el-row class="mt1">
              <el-col :span="4" style="display: flex; justify-content: center">
                <el-radio-group
                  v-model="queryParams.type"
                  @change="changeQuery"
                >
                  <el-radio :value="1">按年</el-radio>
                  <el-radio :value="0">按月</el-radio>
                </el-radio-group>
              </el-col>
              <el-col :span="12">
                <el-date-picker
                  v-model="queryParams.yearMonth"
                  :type="queryParams.type == 1 ? 'year' : 'month'"
                  placeholder="请选择"
                  :format="queryParams.type == 1 ? 'YYYY年' : 'YYYY年MM月'"
                  :value-format="queryParams.type == 1 ? 'YYYY' : 'YYYY-MM'"
                  @change="getComList"
                />
              </el-col>
            </el-row>
            <el-row class="mt1" :gutter="50">
              <el-col :span="12">
                <div
                  ref="satisfaction"
                  :style="
                    queryParams.type == 1 ? 'height: 180px' : 'height: 360px'
                  "
                />
                <div
                  class="el-table el-table--enable-row-hover el-table--medium"
                  v-if="queryParams.type == 1"
                >
                  <div ref="evatrend" style="height: 180px" />
                </div>
              </el-col>
              <el-col :span="12">
                <div
                  class="el-table el-table--enable-row-hover el-table--medium"
                >
                  <div ref="evatotal" style="height: 360px" />
                </div>
              </el-col>
            </el-row>
            <div
              class="mt2 el-table el-table--enable-row-hover el-table--medium"
            >
              <el-table v-loading="loading" :data="tableList" border>
                <el-table-column
                  label="社区名称"
                  prop="communityName"
                  align="center"
                />
                <el-table-column
                  label="评价总数"
                  prop="cmySumCount"
                  align="center"
                >
                  <template #default="scope">
                    <span style="color: #038afe">{{
                      scope.row.cmySumCount
                    }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="满意"
                  prop="cmySatisfiedCount"
                  align="center"
                />
                <el-table-column
                  label="一般"
                  prop="cmyGeneralCount"
                  align="center"
                />
                <el-table-column
                  label="不满意"
                  prop="cmyDissatisfiedCount"
                  align="center"
                />
              </el-table>
            </div>
          </template>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="EvaluationStatistics">
import { listPoliceBySearch } from "@/api/community/police";
import {
  getEvaluationStat,
  userEvaluationStat,
  userEvaluationStatSort,
} from "@/api/crowdInfo/evaluation";
import {
  initSatisfactionChart,
  initEvatrendChart,
  initEvatotalChart,
  initUserEvaYearChart,
  initUserEvaNumSortChart,
} from "./chart";
import * as echarts from "echarts";
import dayjs from "dayjs";
import { onMounted } from "vue";
import { nextTick } from "vue";

const { proxy } = getCurrentInstance();
const current = ref(0);
const satisfaction = ref(null);
const evatrend = ref(null);
const evatotal = ref(null);
const evayear = ref(null);
const evanum = ref(null);
const tableList1 = ref([]); //个人
const tableList = ref([]); //社区
const policeUserId = ref(undefined);
const polices = ref([]);
const data = reactive({
  queryParams: {
    type: 0, //0月 1年，默认月
    yearMonth: dayjs(new Date()).format("YYYY-MM"),
  },
  userYears: dayjs(new Date()).format("YYYY"),
  scoreStar: 10,
});
const { queryParams, userYears, scoreStar } = toRefs(data);

function getComList() {
  proxy.$modal.loading("正在加载群众评价统计图表数据，请稍候！");
  getEvaluationStat(queryParams.value)
    .then((response) => {
      proxy.$modal.closeLoading();
      const { data } = response;
      // 满意度
      const satisfactionIntance = echarts.init(satisfaction.value, "macarons");
      satisfactionIntance.setOption(
        initSatisfactionChart(
          data.satisfiedCount, // 不满意数量
          data.generalCount, // 一般数量
          data.dissatisfiedCount, // 满意数量
          data.sumCount // 满意度统计数量总和
        )
      );

      satisfactionIntance.resize();
      // 服务评价趋势
      if (queryParams.value.type == 1) {
        const evatrendIntance = echarts.init(evatrend.value, "macarons");
        let xdata = [];
        let ydata = [];
        data.yearStatisticsVos = data.yearStatisticsVos ?? [];
        if (data.yearStatisticsVos.length) {
          data.yearStatisticsVos.forEach((item) => {
            xdata.push(item.month);
            ydata.push(item.monthCount - 0);
          });
        }
        evatrendIntance.setOption(initEvatrendChart(xdata, ydata));
      }

      // 评价总数
      const evatotalInstance = echarts.init(evatotal.value, "macarons");
      let xdata = [];
      let ydata = [];
      let total = 0;
      data.communityChartVos = data.communityChartVos ?? [];
      if (data.communityChartVos.length) {
        data.communityChartVos.forEach((item) => {
          xdata.push(item.communityName);
          ydata.push(item.communityCount - 0);
          total += item.communityCount - 0;
        });
      }
      evatotalInstance.setOption(initEvatotalChart(xdata, ydata, total));

      // 初始化表格数据
      tableList.value = data.communityTableVos ?? [];
      window.addEventListener("resize", () => {
        satisfactionIntance.resize();
        evatrendIntance.resize();
        evatotalInstance.resize();
      });
    })
    .catch((err) => {
      proxy.$modal.closeLoading();
    });
}

function changeQuery() {
  if (queryParams.value.type == 1) {
    queryParams.value.yearMonth = String(new Date().getFullYear());
  } else {
    queryParams.value.yearMonth = dayjs(new Date()).format("YYYY-MM");
  }
  getComList();
}

function getUserList() {
  initUserEvaStat();
  initUserEvaStatSort();
}

function initUserEvaStat() {
  proxy.$modal.loading("正在加载群众评价统计图表数据，请稍候！");
  userEvaluationStat({
    ...{ policeUserId: policeUserId.value },
    ...{ years: userYears.value },
  })
    .then((response) => {
      proxy.$modal.closeLoading();
      const { data } = response;
      nextTick(() => {
        // 评价总数
        const evayearInstance = echarts.init(evayear.value, "macarons");
        let xdata = [];
        let ydata = [];
        let chartData = data.yearVos ?? [];
        if (chartData.length) {
          chartData.forEach((item) => {
            xdata.push(item.month + "月");
            ydata.push(item.monthCount);
          });
        }
        evayearInstance.setOption(
          initUserEvaYearChart(
            xdata,
            ydata,
            `${data.userName ?? ""}-${data.badgeNumber ?? ""}`
          )
        );
        // 初始化表格数据
        tableList1.value = data.statisticsVos ?? [];
        window.addEventListener("resize", () => {
          evayearInstance.resize();
        });
      });
    })
    .catch((err) => {
      proxy.$modal.closeLoading();
    });
}

// 纵向柱状图
function initUserEvaStatSort() {
  userEvaluationStatSort({
    ...{ scoreStar: scoreStar.value },
    ...{ years: userYears.value },
  })
    .then((response) => {
      const { data } = response;
      let list = data ?? [];
      let xdata = [];
      let ydata = [];
      let comArr = [];
      if (list.length) {
        list.forEach((item) => {
          xdata.push(item.userName);
          ydata.push(item.communityCount);
          comArr.push(item.communityName);
        });
      }
      const evanumInstance = echarts.init(evanum.value, "macarons");
      evanumInstance.setOption(initUserEvaNumSortChart(xdata, ydata, comArr));

      window.addEventListener("resize", () => {
        evanumInstance.resize();
      });
    })
    .catch((err) => {
      proxy.$modal.closeLoading();
    });
}

// 民警列表
function listPolice() {
  listPoliceBySearch({ key: "" })
    .then((response) => {
      const { data } = response;
      polices.value = data;
    })
    .catch((err) => {});
}

function resetQuery() {
  tableList1.value = [];
  policeUserId.value = undefined;
  userYears.value = dayjs(new Date()).format("YYYY");
  const evayearInstance = echarts.init(evayear.value, "macarons");
  evayearInstance.setOption(initUserEvaYearChart());
  window.addEventListener("resize", () => {
    evayearInstance.resize();
  });
  initUserEvaStatSort();
}

onMounted(() => {
  listPolice();
  // getComList();
  if (policeUserId.value) {
    getUserList();
  } else {
    const evayearInstance = echarts.init(evayear.value, "macarons");
    evayearInstance.setOption(initUserEvaYearChart());
    window.addEventListener("resize", () => {
      evayearInstance.resize();
    });
    initUserEvaStatSort();
  }
});
</script>
<style lang="scss" scoped>
.head {
  font-weight: bold;
  font-size: 1.5em;
  color: #000;
  margin-bottom: 15px;
}
</style>
